import Component from '@teld/q-components/Date';
import useMappingProps from 't/common/hooks/useMappingProps';
import {
  commonProps,
  fixNameSpace,
  pickOwnForBasicComponent,
} from 't/common/utils';
import { defineComponent, onMounted, ref } from 'vue';
import styles from './index.module.scss';
import './index.scss';
import { Calendar } from '@teld/tm-components/Calendar'
import { useQuasar } from '@teld/q-components';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';

export * from '@teld/q-components/Date';


export default defineComponent({
  name: fixNameSpace(Component.name),
  props: {
    ...commonProps,
    ...Component.props,
    demo: {
      type: String,
      default() {
        return '';
      },
    },
    type: {
      type: String,
      default() {
        return 'single';
      },
    },
  },
  emits: ['confirm', 'close'],
  setup(props, { attrs, emit, expose, slots }) {
    const refComponent = ref();
    const [mappingProps, mappingExpose] = useMappingProps(props);
    const $q = useQuasar();
    const calendarShow = ref(false);
    mappingExpose.calendarShow = calendarShow;
    expose(mappingExpose);
    dayjs.extend(customParseFormat);

    onMounted(() => {});

    const onConfirm = values => {
      if (mappingProps.type === 'range') {
        let obj = {
          from: dayjs(values[0]).format('YYYY/MM/DD'),
          to: dayjs(values[1]).format('YYYY/MM/DD'),
        };
        mappingProps.modelValue = obj;
      }
      if (mappingProps.type === 'multiple') {
        let array = [...values];
        array.forEach(item => {
          item = dayjs(item).format('YYYY/MM/DD');
        });
        mappingProps.modelValue = array;
      }
      if (mappingProps.type === 'single') {
        mappingProps.modelValue = dayjs(values).format('YYYY/MM/DD');
      }
      emit('update:modelValue', mappingProps.modelValue);
      emit('confirm', values);
    };

    const onClose = () => {
      calendarShow.value = false;
      emit('close');
    };

    return () => {
      return $q.screen.xs ? (
        <Calendar
          show={calendarShow.value}
          type={mappingProps.type}
          onConfirm={onConfirm}
          onClose={onClose}
          switch-mode='year-month'
        />
      ) : (
        <Component
          ref={refComponent}
          {...attrs}
          {...pickOwnForBasicComponent(mappingProps, Component.props, attrs)}
          class={['t-date', styles.module]}
          v-show={mappingProps.visible}
        >
          {slots}
        </Component>
      );
    };
  },
});
